/**
 * 项目为常用方法的集合
 */
import constant from '@/constant'
import validate from '@/utils/open/validate'
import store from '@/store/index'
import vuxTool from '@/utils/open/vux-plugin'
import router from '@/router'
import { JSEncrypt } from 'jsencrypt'
// import Vue from 'vue'

// var isThrottle = true
// var testClick = null
export default {
  /**
   * 清除图片/视频 数据
   */
  cleanMediaData(that, upLoadImgDom) {
    // console.log('清除图片/视频 数据')
    // console.log('3')
    that.$nextTick(() => {
      // console.log('4')
      if (upLoadImgDom) {
        if (upLoadImgDom.length > 0) {
          upLoadImgDom[0].cleanData()
        } else {
          upLoadImgDom.cleanData() // 清空图片上传数据
        }
      }
    })
  },
  /**
   * 判断当前选中角色 是否加入班级
   * @param {Boolean} isCheckClassId 是否监测 （园长不需要判断）
   */
  checkPermissionByClassId(isCheckClassId) {
    let flag = true
    const curSelectRole = store.state.user.curSelectRole || {}
    if (isCheckClassId) { // 老师角色入口需要判断是否已加入班级，否则直接跳转 提示页面
      if (!curSelectRole.data.classId) {
        router.push({ name: 'NotJoinClass' })
        flag = false
      }
    }
    return flag
  },
  /**
   * 返回校园页
   * @param {Boolean} isReplace 是否replace 默认 true
   */
  goCampus(isReplace) {
    isReplace = !!isReplace
    if (isReplace) {
      router.replace({ name: 'Campus' })
    } else {
      router.push({ name: 'Campus' })
    }
  },
  /**
   * 返回首页
   * @param {Boolean} isReplace 是否replace 默认 true
   */
  goHome(isReplace) {
    isReplace = !!isReplace
    if (isReplace) {
      router.replace({ name: 'Home' })
    } else {
      router.push({ name: 'Home' })
    }
  },
  /**
   * 防抖，在频繁触发某些事件，导致大量的计算或者非常消耗资源的操作的时候，防抖可以强制在一段连续的时间内只执行一次
   * */
  debounce(fn, delay) {
    // console.log('防抖1')
    const _delay = delay || 200
    let timer
    return function() {
      // console.log('防抖2')
      const th = this
      const args = arguments
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(function() {
        timer = null
        fn.apply(th, args)
        // console.log('防抖3')
      }, _delay)
    }
  },
  /**
   * 函数节流，指定時間內只執行一次
   * @param {Funtion} fn 回调函数
   * @param {Number} interval
   */
  throttle(fn, interval = 300) {
    return function() {
      // console.log('throttle1')
      if (fn.isThrottle) return
      // console.log('throttle2')
      fn.isThrottle = true
      fn.apply(this, arguments)
      setTimeout(() => {
        // console.log('throttle3')
        fn.isThrottle = false
        // store.dispatch('sys/UpdateIsTransition', false) // 启动页面切换转场
      }, interval)
    }
  },
  /**
   * 操作指定name的路由的元信息
   * @param parentName
   * @param name
   * @param keepAlive
   * 状态判断
   * @param type
   */
  getTypeName(type) {
    const arr = [
      { dictinfoKey: '夏令营', dictinfoValue: '1' }, { dictinfoKey: '体验课', dictinfoValue: '2' }, { dictinfoKey: '其他', dictinfoValue: '3' }
    ]
    const temp = arr.find((item) => {
      return item.dictinfoValue == type
    })
    return temp.dictinfoKey
  },
  /**
   * html对img处理
   * @param str
   */
  htmlCut(str) {
    const c1 = str.replace(/<img width="100%"/g, '<img')
    const c2 = c1.replace(/<img/g, '<img width="100%"')
    return c2
  },
  /**
   * 判断某个值是否在数组里
   * @param value
   * @param validList
   */
  oneOf(value, validList) {
    for (let i = 0; i < validList.length; i++) {
      if (value === validList[i]) {
        return true
      }
    }
    return false
  },
  /**
   * 通过数组键值删除元素
   * @param {Array} arr 数组
   * @param {String} key 匹配的键
   * @param {String} val 匹配的值
   */
  removeByKey(arr, key, val) {
    const index = this.findKey(arr, key, val)
    if (index > -1) {
      arr.splice(index, 1)
    }
  },
  /**
   * 返回数组匹配到的索引
   * @param {Array} arr 数组
   * @param {String} key 匹配的键
   * @param {String} val 匹配的值
   * @return {Number} index 返回匹配到的索引
   */
  findKey(arr, key, val) {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i][key] === val) {
        return i
      }
    }
    return -1
  },
  /**
   * 公钥加密
   * @param key
   * @param value
   */
  jsEncryptCode(value) {
    const encrypt = new JSEncrypt()
    encrypt.setPublicKey(
      '-----BEGIN PUBLIC KEY-----\n' +
      'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw5fFGwk4eqgen3IUQs9m\n' +
      'sE7G8rhQvzpVtvt/HQoa/We43rrWC3NfV9cQU18+8kMGBHEOOAbnDVemxCm28goN\n' +
      'Lmkx74H6nYLfIxrrGC+AFffRFaAfPzp2m712clymuZEeSM01tpgp1XgIBuWBRV30\n' +
      '94Cba1XnJw3IXbICdkvIkmvtkUnkbnplKjDUDZ4whG5OG0FsOUODgArc//3xj8I3\n' +
      'MOQytp/0JqEgIV9ejkpRdIqZL3QIZDEFlfsyV6nhsKYutkSVBvzE4NAx6bJUl4cc\n' +
      'BfaxmkysmGzXr6Mpyi+WBT3oYL6chhb+y/Nzuim0WOEAZZfBnWK/VlTuU9NWhWFW\n' +
      '8QIDAQAB\n' +
      '-----END PUBLIC KEY-----'
    )
    return encrypt.encrypt(value)
  },
  /**
   * 清空用户账户数据
   * 退出，密码出错都会执行
   */
  clearAccountFn() {
    const sessionArr = [
      'token', 'refreshToken', 'userAccount', 'tokenUuid', 'bannerList', 'isCutOutUrl', 'routerNameObj',
      'historyCount', 'classIsSelect', 'noticePublishObject', 'noticePublishObjectSelectTab'] // 需要清除的存储数据
    sessionArr.forEach(k => {
      if (k) {
        window.sessionStorage.removeItem(k)
      }
    })
    const localStorageArr = ['noticePublishData', 'albumPublishData', 'homeworkPublishData']
    localStorageArr.forEach(k => {
      if (k) {
        window.localStorage.removeItem(k)
      }
    })
    store.dispatch('campus/EmptyCampus') // 清除首页缓存数据
    store.dispatch('user/LoginOut') // 清除相关数据 clean
    store.dispatch('user/ClearPermissionsAll') // 清除权限数据
    store.dispatch('user/CleanWeChatInfo') // 清除微信信息 clean
    store.dispatch('sys/UpdateTimerChangeToken', null) // 清除定时刷新token 定时器
    router.push({ name: 'Login' })
  },
  /*
    * 表单验证
    * tipArr: 要验证的表单字段+名字，json格式
    * data: 要验证的表单值，json格式
    * return true: 验证通过； false: 验证不通过
    * that
    * */
  validationForm(tipArr, data) {
    // debugger
    for (const k in tipArr) {
      if (k && tipArr.hasOwnProperty(k)) {
        let arr = []
        let key
        let val
        let type
        if (k.indexOf('.') > -1) { // 为这类设置 tipArr['noticeSign.endTime'] = '请选择截止时间！'
          arr = k.split('.')
          key = arr[0]
          val = data[arr[0]][arr[1]]
        } else {
          arr = k.split('-')
          key = arr[0]
          type = arr[1]
          val = data[key]
        }

        if (typeof val === 'undefined' || val === null || val === '' || val.length <= 0) { // 为空
          let text = '请输入'
          // debugger
          if (tipArr[k].indexOf('请') > -1)text = ''
          vuxTool.toast(text + tipArr[k])
          // if (document.querySelector('#' + key + 'Id')) {
          //   document.querySelector('#' + key + 'Id').focus()
          // }
          return false
        } else { // 不为空
          if (type) {
            tipArr[k] = tipArr[k].replace('请输入', '')
            tipArr[k] = tipArr[k].replace('请选择', '')
            if (type === 'phone') { // 手机验证
              const reg = /^1\d{10}$/
              if (!reg.test(val)) {
                vuxTool.toast(tipArr[k] + '有误')
                return false
              }
            } else if (type === 'mail') { // 邮箱验证
              const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
              if (!reg.test(val)) {
                vuxTool.toast(tipArr[k] + '有误')
                return false
              }
            } else if (type === 'IDCard') { // 身份证验证
              const obj = validate.isCardid(val)
              if (!obj.status) {
                vuxTool.toast(obj.text)
                return obj.status
              }
              // return obj.status
            }
          }
        }
      }
    }
    return true
  },
  /**
   * 获取链接末尾参数
   * @param {string}  num：1. hash
   */
  getCurPathParam(num) {
    // debugger
    const newObj = {}
    if (num === 1) {
      const url = location.hash// 获取链接 #/...? 后的字符串，并组合成 json 格式
      const reg = /#\/.*?\?/gi

      // if(url.indexOf('?') !== -1){
      const res = url.match(reg)
      if (res && url.match(reg).length > 0) {
      // let str = url.substr(3);
        let str = url.replace(reg, '')
        str = str.replace(/#\/$/, '')
        const strs = str.split('&')
        for (let i = 0; i < strs.length; i++) {
          newObj[strs[i].split('=')[0]] = (strs[i].split('=')[1])
        }
      }
    } else {
      let url = location.search// 获取链接 #/...? 后的字符串，并组合成 json 格式
      if (url) {
        url = url.substr(1)
        const obj = url.split('&')
        let arr = []
        for (const key of obj) {
          arr = key.split('=')
          newObj[arr[0]] = arr[1]
        }
      }
    }
    return newObj
  },
  /**
   * 查找父元素
   * @param {Object} child 目标dom元素
   * @param {String} parentCls 父元素的class
   */
  getParentByClass(child, parentCls) {
    if (!child) {
      return child
    }
    const pNode = child.parentNode
    if (pNode.classList.length && pNode.classList.contains(parentCls)) {
      return pNode
    } else {
      return this.getParentByClass(pNode, parentCls)
    }
  },
  getRect(el) {
    if (el instanceof window.SVGElement) {
      const rect = el.getBoundingClientRect()
      return {
        top: rect.top,
        left: rect.left,
        width: rect.width,
        height: rect.height
      }
    } else {
      return {
        top: el.offsetTop,
        left: el.offsetLeft,
        width: el.offsetWidth,
        height: el.offsetHeight
      }
    }
  },
  /**
   * 初始化swiper
   * @param that
   * @param conf
   * @param fn
   */
  initSwiperConfig(that, conf, fn) {
    // eslint-disable-next-line
    const _this = this
    const config = { // swiper的参数配置
      pagination: { // ‘bullets’  圆点（默认） ‘fraction’  分式  ‘progressbar’  进度条 ‘custom’ 自定义
        el: '.swiper-pagination'
      },
      direction: 'horizontal', // 平(horizontal)或垂直(vertical)
      slidesPerView: 'auto',
      centeredSlides: true,
      noSwiping: false,
      // loop: true,
      autoplay: {
        delay: 1000,
        disableOnInteraction: false // 用户操作swiper之后，是否禁止autoplay。默认为true：停止
      },
      observer: true,
      observeParents: true,
      speed: 1000,
      coverflow: {
        rotate: 0,
        stretch: -30,
        depth: 100,
        modifier: 0.7,
        slideShadows: false
      },
      initialSlide: 0,
      runCallbacksOnInit: true, // 初始化时不触发 slideChange
      on: {
        slideChange(e) {
          if (this.activeIndex || this.activeIndex === 0) {
            store.dispatch('swiper/updateSwiperActiveIndex', this.activeIndex) // 当前显示图片索引
          }
        }
      },
      preloadImages: false, // 默认为true，Swiper会强制加载所有图片。
      isShowCustiomPagination: true // 是否显示自定义分页器 默认显示
    }

    for (const key in conf) {
      if (conf.hasOwnProperty(key)) {
        config[key] = conf[key]
      }
    }
    fn(config)
  },
  /**
   * 获取永久本地缓存
   * @param name
   */
  getLocalCache(key) {
    return window.localStorage.getItem(key) || {}
  },
  /**
   * 获取永久本地缓存
   * @param name
   */
  setLocalCache(key, value) {
    return window.localStorage.setItem(key, value)
  },
  /**
   * 获取token
   */
  getToken() {
    return this.getKeyVal('user', 'token', 'sessionStorage')
  },
  /**
   * 判断是否判断微信环境，另外，若微信权限注册成功，也会设置 isWechat 为 true
   */
  isWechatClient() {
    let flag = false
    if (navigator.userAgent.toLowerCase().indexOf('micromessenger') > -1) { // 是微信环境
      flag = true
    }
    return flag
  },
  /**
   * 截取链接末尾参数
   */
  cutOutUrl() {
    // 截取链接末尾参数(保证每次打开浏览器只截取一遍)
    const isCutOutUrl = this.getKeyVal('user', 'isCutOutUrl', 'sessionStorage')
    if (!isCutOutUrl) {
      // const num = process.env.ENV_CONFIG === 'dev' ? 1 : 2 // 开发环境和生产环境的连接不一样，获取末尾参数方式也不一样
      const urlParam = this.getCurPathParam(1) || {}
      // console.log('urlParam:', urlParam)
      if (urlParam.openId) {
        this.setKeyVal('user', 'isCutOutUrl', true, 'sessionStorage')
        this.setKeyVal('user', 'firstUrlParam', urlParam, 'sessionStorage')
      }
    }
  },
  /**
   * 返回上一页（若有上一页返回上一页，没则回到首页）
   */
  goBack(that) {
    const query = that.$route.query
    if (query.backHome) {
      this.goHome(true)
    } else {
      if (window.history.length <= 1) {
        router.push({ path: '/' })
        return false
      } else {
        router.go(-1)
      }
    }
    // alert('goBack-1')
    // if ((navigator.userAgent.indexOf('MSIE') >= 0) && (navigator.userAgent.indexOf('Opera') < 0)) { // IE
    //   // alert('goBack-1.1,history.length', history.length)
    //   if (history.length > 0) {
    //     // alert('goBack-1.2')
    //     this.goHome(true)
    //   } else {
    //     // alert('goBack-1.3')
    //     this.goCampus(true)
    //   }
    // } else { // 非IE浏览器
    //   const historyLen = window.history.length
    //   // alert('goBack-2.01,window.history:' + JSON.stringify(window.history))
    //   // alert('goBack-2.02,window.history.length:' + historyLen)
    //   // console.log('goBack-2.03,window.history:' + window.history)
    //   // console.log('goBack-2.04,historyLen:' + historyLen)
    //   if (navigator.userAgent.indexOf('Firefox') >= 0 ||
    //     navigator.userAgent.indexOf('Opera') >= 0 ||
    //     navigator.userAgent.indexOf('Safari') >= 0 ||
    //     navigator.userAgent.indexOf('Chrome') >= 0 ||
    //     navigator.userAgent.indexOf('WebKit') >= 0) {
    //     if (historyLen > 1) {
    //       // console.log('goBack-2.1')
    //       // alert('goBack-2.1')
    //       // window.history.go(-1)
    //       router.go(-1)
    //     } else {
    //       // console.log('goBack-2.2')
    //       // alert('goBack-2.2')
    //       this.goHome(true)
    //     }
    //   } else { // 未知的浏览器
    //     // alert('goBack-3')
    //     if (historyLen > 1) {
    //       // alert('goBack-3.1')
    //       // window.history.go(-1)
    //       router.go(-1)
    //     } else {
    //       // alert('goBack-3.2')
    //       this.goHome(true)
    //     }
    //   }
    // }
  },
  /**
   * 存储 store , sessionStorage
   * 注意传参格式
   * @param {String} module
   * @param {String} key
   * @param {String} val
   * @param {String} storeName 可不传 localStorage,sessionStorage
   */
  setKeyVal(module, key, val, storeName) {
    // debugger
    const fnName = module + '/Update' + key.substring(0, 1).toUpperCase() + key.substring(1)
    const type = validate.judgeTypeOf(val)
    if (type !== 'String' && type !== 'Undefined' && type !== 'Null') {
      store.dispatch(fnName, val)
      if (storeName) {
        let val1 = this.deepCloneObj(val)
        val1 = JSON.stringify(val1)
        window[storeName].setItem(key, val1)
      }
    } else {
      if (storeName) {
        window[storeName].setItem(key, val)
      }

      try {
        if (val.match(/\{/)) { // 若匹配到{则说明是json字符
          val = JSON.parse(val)
        }
      } catch (e) {
        // dosome...
      } finally {
        if (type === 'String') {
          store.dispatch(fnName, val)
        }
      }
    }
  },
  /**
   * 获取 store,sessionStorage
   * @param {String} module 模块名字
   * @param {String} key state属性
   * @param {Boolean} storeName localStorage,sessionStorage
   */
  getKeyVal(module, key, storeName) {
    let val = store.state[module][key]
    if (validate.isNull(val) && !validate.isNull(storeName)) {
      val = window[storeName].getItem(key)
      if (!validate.isNull(val)) {
        this.setKeyVal(module, key, val)

        const type = validate.judgeTypeOf(val)
        if (type === 'String' && val.match(/\{/)) { // 若匹配到{则说明是json字符
          val = JSON.parse(val)
        }
      }
    }
    return val
  },
  /**
   * 常量引用
   */
  static: constant,
  /**
   * 对象，深拷贝
   * @param {Object} obj
   */
  deepCloneObj(data) {
    const type = this.getType(data)
    let obj
    if (type === 'array') {
      obj = []
    } else if (type === 'object') {
      obj = {}
    } else {
      return data
    }
    if (type === 'array') {
      for (let i = 0, len = data.length; i < len; i++) {
        obj.push(this.deepCloneObj(data[i]))
      }
    } else if (type === 'object') {
      for (const key in data) {
        if (data.hasOwnProperty(key)) {
          obj[key] = this.deepCloneObj(data[key])
        }
      }
    }
    return obj
  },

  /**
   * 获取对象属性类型
   *
   * @param e
   * @returns {string}
   */
  getType(e) {
    if (e == null) {
      return ''
    }
    if (e.constructor === Array) {
      return 'array'
    } else if (e.constructor === Object) {
      return 'object'
    } else if (e.constructor === String) {
      return 'string'
    } else if (e.constructor === Number) {
      return 'number'
    } else if (e.constructor === Boolean) {
      return 'boolean'
    }
    return ''
  },
  /**
   * 对象，浅拷贝
   * @param {Object} obj
   */
  easyCloneObj(obj) {
    const newObj = {}
    for (const i in obj) {
      if (i && obj.hasOwnProperty(i)) {
        newObj[i] = obj[i]
      }
    }
    return newObj
  },
  /**
   * 设置缓存
   * @param key
   * @param value
   */
  setCache(key, value) {
    return new Promise(resolve => {
      window.sessionStorage.setItem(key, JSON.stringify(value))
      resolve()
    })
  },
  /**
   * 获取缓存
   * @param key
   */
  getCache(key) {
    const item = window.sessionStorage.getItem(key)
    if (validate.isNull(item)) {
      return ''
    }
    return JSON.parse(window.sessionStorage.getItem(key))
  },
  /**
   * 获取缓存
   * @param {String} key
   */
  getTokenUuid() {
    let val = this.getCache('tokenUuid')
    if (!val) {
      val = this.uuid()
      this.setCache('tokenUuid', val)
    }
    return val
  },
  /**
   * 获取uuid
   * @returns {string}
   */
  uuid() {
    function S4() {
      return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
    }
    return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4())
  },
  /**
   * 拼接头像参数，获取头像地址
   * @param img
   * @returns {*}
   */
  getHeadImage(imgUrl) {
    // /static/img/ 为本地默认头衔路径
    // debugger
    if (imgUrl && imgUrl.indexOf('http') <= -1 && imgUrl.indexOf('/static/img/') <= -1) {
      imgUrl = this.cutThumbnailSmall(imgUrl, constant.thumbnail.smaller) // 添加缩略图
    }
    return imgUrl
  },
  /**
   * 缩略图 小图
   * @param that
   * @param img
   * @param smallerImg 最小尺寸
   * @returns {*}
   */
  cutThumbnailSmall(imgUrl, smallerImg) {
    // debugger
    if (imgUrl && imgUrl.indexOf('http') <= -1) {
      imgUrl = constant.file_ctx + imgUrl
    }
    // const reg = /\.(swf|avi|flv|mpg|rm|mov|wav|asf|3gp|mkv|rmvb|wmv|mp4|ogg)$/i
    const reg = constant.videoReg
    if (imgUrl.match(reg)) {
      // ...
    } else if (!imgUrl || imgUrl.indexOf(constant.thumbnail.small) > -1 || imgUrl.indexOf(constant.thumbnail.smaller) > -1 || imgUrl.indexOf(constant.thumbnail.large) > -1) {
      // return imgUrl
    } else {
      // console.log(imgUrl, constant.thumbnail.small)
      if (smallerImg) {
        imgUrl = imgUrl += constant.thumbnail.smaller
      } else {
        imgUrl = imgUrl += constant.thumbnail.small
      }
    }
    return imgUrl
  },
  /**
   * 缩略图 大图
   * @param that
   * @param img
   * @returns {*}
   */
  cutThumbnailLarge(imgUrl) {
    // debugger
    if (!imgUrl || imgUrl.indexOf(constant.thumbnail.large) > -1) {
      return imgUrl
    }
    imgUrl = imgUrl += constant.thumbnail.large
    return imgUrl
  },
  /**
   * 缩略图 小图转大图
   * @param that
   * @param img
   * @returns {*}
   */
  cutThumbnailSmallToLarge(imgUrl) {
    // debugger
    if (!imgUrl || imgUrl.indexOf(constant.thumbnail.large) > -1) {
      return imgUrl
    }
    imgUrl = imgUrl.replace(constant.thumbnail.small, constant.thumbnail.large)
    return imgUrl
  },
  /**
   * 获取默认头像
   */
  getDefaultHeadImage(user) {
    // console.log('getDefaultHeadImage')
    // const guatdianDefault = [{ code: '1428', src: 'static/img/default/icon-baby-boy.png' }, { code: '1427', src: 'static/img/default/icon-baby-girl.png' }]
    // const staff = [{ code: '1428', src: 'static/img/default/icon-male-teacher.png' }, { code: '1427', src: 'static/img/default/icon-female-teacher.png' }]
    let arr = []
    // 1538：家长端; 1537: 教师端
    if (user.identityType) {
      if (user.identityType === '1538') {
        arr = [
          { code: '1428', src: '/static/img/default/icon-baby-boy.png' },
          { code: '1429', src: '/static/img/default/icon-baby-girl.png' }
        ]
      } else {
        arr = [
          { code: '1428', src: '/static/img/default/icon-male-teacher.png' },
          { code: '1429', src: '/static/img/default/icon-female-teacher.png' }
        ]
      }
    } else {
      user.sexObj = { imgUrl: '/static/img/svg/icon-tourist.svg' }
      return
    }
    let imgUrl = {}
    imgUrl = arr.find((item) => {
      // debugger
      return item.code === user.sex
    })
    user.sexObj = { imgUrl: imgUrl && imgUrl.src || './static/img/svg/icon-tourist.svg' }
  },
  /**
   * 对未读数量进行处理
   * @param {Object} obj
   * @param value
   */
  setUnread(obj, value, type) {
    if (obj[value] === 0) {
      store.commit('user/REDUCE_UNREADLIST', type)
      store.dispatch('user/UpdateUnreadNum', store.state.user.unreadNum - 1)
    }
  },
  getHtmlText(val) { // 正则表达式截取html标签内的内容
    const reg = /<[^<>]+>/g
    val = val.replace(reg, '')
    val = val.replace(/&nbsp;/g, ' ')
    val = this.faceTopic2Img(val)
    return val
  },
  setCharactersTextImg(val) { // 将回车，空格替换成网页特殊字符，以及替换特殊图片字符为图片 // 将特殊字符，转为表情图
    val = val.replace(/[\r\n]/g, '<br/>').replace(/\s/g, '&nbsp;')
    val = this.faceTopic2Img(val)
    return val
  },
  setCharactersText(val) { // 将回车，空格替换成网页特殊字符
    return val.replace(/[\r\n]/g, '<br/>').replace(/\s/g, '&nbsp;')
  },
  faceTopic2Img(content) {
    const path = './static/img/face/'
    content = content.replace(/\[微笑\]/g, "<img data-title='[微笑]'src='" + path + "weixiao.gif'/>")
      .replace(/\[撇嘴\]/g, "<img data-title='[撇嘴]' src='" + path + "pizui.gif'/>")
      .replace(/\[色\]/g, "<img data-title='[色]' src='" + path + "se.gif'/>")
      .replace(/\[发呆\]/g, "<img data-title='[发呆]' src='" + path + "fadai.gif'/>")
      .replace(/\[得意\]/g, "<img data-title='[得意]' src='" + path + "deyi.gif'/>")
      .replace(/\[流泪\]/g, "<img data-title='[流泪]' src='" + path + "liulei.gif'/>")
      .replace(/\[害羞\]/g, "<img data-title='[害羞]' src='" + path + "haixiu.gif'/>")
      .replace(/\[闭嘴\]/g, "<img data-title='[闭嘴]' src='" + path + "bizui.gif'/>")
      .replace(/\[睡觉\]/g, "<img data-title='[睡觉]' src='" + path + "shuijiao.gif'/>")
      .replace(/\[睡\]/g, "<img data-title='[睡]' src='" + path + "shuijiao.gif'/>")
      .replace(/\[大哭\]/g, "<img data-title='[大哭]' src='" + path + "daku.gif'/>")
      .replace(/\[尴尬\]/g, "<img data-title='[尴尬]' src='" + path + "gangga.gif'/>")
      .replace(/\[大怒\]/g, "<img data-title='[大怒]' src='" + path + "danu.gif'/>")
      .replace(/\[发怒\]/g, "<img data-title='[发怒]' src='" + path + "danu.gif'/>")
      .replace(/\[调皮\]/g, "<img data-title='[调皮]' src='" + path + "tiaopi.gif'/>")
      .replace(/\[呲牙\]/g, "<img data-title='[呲牙]' src='" + path + "ciya.gif'/>")
      .replace(/\[惊讶\]/g, "<img data-title='[惊讶]' src='" + path + "jingya.gif'/>")
      .replace(/\[难过\]/g, "<img data-title='[难过]' src='" + path + "nanguo.gif'/>")
      .replace(/\[酷\]/g, "<img data-title='[酷]' src='" + path + "ku.gif'/>")
      .replace(/\[冷汗\]/g, "<img data-title='[冷汗]' src='" + path + "lenghan.gif'/>")
      .replace(/\[抓狂\]/g, "<img data-title='[抓狂]' src='" + path + "zhuakuang.gif'/>")
      .replace(/\[吐\]/g, "<img data-title='[吐]' src='" + path + "tu.gif'/>")
      .replace(/\[偷笑\]/g, "<img data-title='[偷笑]' src='" + path + "touxiao.gif'/>")
      .replace(/\[可爱\]/g, "<img data-title='[可爱]' src='" + path + "keai.gif'/>")
      .replace(/\[白眼\]/g, "<img data-title='[白眼]' src='" + path + "baiyan.gif'/>")
      .replace(/\[傲慢\]/g, "<img data-title='[傲慢]' src='" + path + "aoman.gif'/>")
      .replace(/\[饥饿\]/g, "<img data-title='[饥饿]' src='" + path + "er.gif'/>")
      .replace(/\[困\]/g, "<img data-title='[困]' src='" + path + "kun.gif'/>")
      .replace(/\[惊恐\]/g, "<img data-title='[惊恐]' src='" + path + "jingkong.gif'/>")
      .replace(/\[流汗\]/g, "<img data-title='[流汗]' src='" + path + "liuhan.gif'/>")
      .replace(/\[憨笑\]/g, "<img data-title='[憨笑]' src='" + path + "haha.gif'/>")
      .replace(/\[大兵\]/g, "<img data-title='[大兵]' src='" + path + "dabing.gif'/>")
      .replace(/\[奋斗\]/g, "<img data-title='[奋斗]' src='" + path + "fendou.gif'/>")
      .replace(/\[咒骂\]/g, "<img data-title='[咒骂]' src='" + path + "ma.gif'/>")
      .replace(/\[疑问\]/g, "<img data-title='[疑问]' src='" + path + "wen.gif'/>")
      .replace(/\[问\]/g, "<img data-title='[问]' src='" + path + "wen.gif'/>")
      .replace(/\[嘘\]/g, "<img data-title='[嘘]' src='" + path + "xu.gif'/>")
      .replace(/\[晕\]/g, "<img data-title='[晕]' src='" + path + "yun.gif'/>")
      .replace(/\[折磨\]/g, "<img data-title='[折磨]' src='" + path + "zhemo.gif'/>")
      .replace(/\[衰\]/g, "<img data-title='[衰]' src='" + path + "shuai.gif'/>")
      .replace(/\[骷髅\]/g, "<img data-title='[骷髅]' src='" + path + "kulou.gif'/>")
      .replace(/\[敲打\]/g, "<img data-title='[敲打]' src='" + path + "da.gif'/>")
      .replace(/\[打\]/g, "<img data-title='[打]' src='" + path + "da.gif'/>")
      .replace(/\[再见\]/g, "<img data-title='[再见]' src='" + path + "zaijian.gif'/>")
      .replace(/\[擦汗\]/g, "<img data-title='[擦汗]' src='" + path + "cahan.gif'/>")
      .replace(/\[挖鼻\]/g, "<img data-title='[挖鼻]' src='" + path + "wabi.gif'/>")
      .replace(/\[抠鼻\]/g, "<img data-title='[抠鼻]' src='" + path + "wabi.gif'/>")
      .replace(/\[鼓掌\]/g, "<img data-title='[鼓掌]' src='" + path + "guzhang.gif'/>")
      .replace(/\[糗大了\]/g, "<img data-title='[糗大了]' src='" + path + "qioudale.gif'/>")
      .replace(/\[坏笑\]/g, "<img data-title='[坏笑]' src='" + path + "huaixiao.gif'/>")
      .replace(/\[左哼哼\]/g, "<img data-title='[左哼哼]' src='" + path + "zuohengheng.gif'/>")
      .replace(/\[右哼哼\]/g, "<img data-title='[右哼哼]' src='" + path + "youhengheng.gif'/>")
      .replace(/\[哈欠\]/g, "<img data-title='[哈欠]' src='" + path + "haqian.gif'/>")
      .replace(/\[鄙视\]/g, "<img data-title='[鄙视]' src='" + path + "bishi.gif'/>")
      .replace(/\[委屈\]/g, "<img data-title='[委屈]' src='" + path + "weiqu.gif'/>")
      .replace(/\[哭了\]/g, "<img data-title='[哭了]' src='" + path + "ku.gif'/>")
      .replace(/\[快哭了\]/g, "<img data-title='[快哭了]' src='" + path + "kuaikule.gif'/>")
      .replace(/\[阴险\]/g, "<img data-title='[阴险]' src='" + path + "yinxian.gif'/>")
      .replace(/\[亲亲\]/g, "<img data-title='[亲亲]' src='" + path + "qinqin.gif'/>")
      .replace(/\[示爱\]/g, "<img data-title='[示爱]' src='" + path + "kiss.gif'/>")
      .replace(/\[亲吻\]/g, "<img data-title='[亲吻]' src='" + path + "kiss.gif'/>")
      .replace(/\[吓\]/g, "<img data-title='[吓]' src='" + path + "xia.gif'/>")
      .replace(/\[可怜\]/g, "<img data-title='[可怜]' src='" + path + "kelian.gif'/>")
      .replace(/\[菜刀\]/g, "<img data-title='[菜刀]' src='" + path + "caidao.gif'/>")
      .replace(/\[西瓜\]/g, "<img data-title='[西瓜]' src='" + path + "xigua.gif'/>")
      .replace(/\[啤酒\]/g, "<img data-title='[啤酒]' src='" + path + "pijiu.gif'/>")
      .replace(/\[篮球\]/g, "<img data-title='[篮球]' src='" + path + "lanqiu.gif'/>")
      .replace(/\[乒乓\]/g, "<img data-title='[乒乓]' src='" + path + "pingpang.gif'/>")
      .replace(/\[咖啡\]/g, "<img data-title='[咖啡]' src='" + path + "kafei.gif'/>")
      .replace(/\[饭\]/g, "<img data-title='[饭]' src='" + path + "fan.gif'/>")
      .replace(/\[猪头\]/g, "<img data-title='[猪头]' src='" + path + "zhutou.gif'/>")
      .replace(/\[花\]/g, "<img data-title='[花]' src='" + path + "hua.gif'/>")
      .replace(/\[玫瑰\]/g, "<img data-title='[玫瑰]' src='" + path + "hua.gif'/>")
      .replace(/\[凋谢\]/g, "<img data-title='[凋谢]' src='" + path + "diaoxie.gif'/>")
      .replace(/\[爱心\]/g, "<img data-title='[爱心]' src='" + path + "love.gif'/>")
      .replace(/\[心碎\]/g, "<img data-title='[心碎]' src='" + path + "xinsui.gif'/>")
      .replace(/\[蛋糕\]/g, "<img data-title='[蛋糕]' src='" + path + "dangao.gif'/>")
      .replace(/\[闪电\]/g, "<img data-title='[闪电]' src='" + path + "shandian.gif'/>")
      .replace(/\[地雷\]/g, "<img data-title='[地雷]' src='" + path + "zhadan.gif'/>")
      .replace(/\[炸弹\]/g, "<img data-title='[炸弹]' src='" + path + "zhadan.gif'/>")
      .replace(/\[刀\]/g, "<img data-title='[刀]' src='" + path + "dao.gif'/>")
      .replace(/\[足球\]/g, "<img data-title='[足球]' src='" + path + "qiu.gif'/>")
      .replace(/\[虫\]/g, "<img data-title='[虫]' src='" + path + "chong.gif'/>")
      .replace(/\[瓢虫\]/g, "<img data-title='[瓢虫]' src='" + path + "chong.gif'/>")
      .replace(/\[便便\]/g, "<img data-title='[便便]' src='" + path + "dabian.gif'/>")
      .replace(/\[月亮\]/g, "<img data-title='[月亮]' src='" + path + "yueliang.gif'/>")
      .replace(/\[太阳\]/g, "<img data-title='[太阳]' src='" + path + "taiyang.gif'/>")
      .replace(/\[礼物\]/g, "<img data-title='[礼物]' src='" + path + "liwu.gif'/>")
      .replace(/\[拥抱\]/g, "<img data-title='[拥抱]' src='" + path + "yongbao.gif'/>")
      .replace(/\[强\]/g, "<img data-title='[强]' src='" + path + "qiang.gif'/>")
      .replace(/\[弱\]/g, "<img data-title='[弱]' src='" + path + "ruo.gif'/>")
      .replace(/\[握手\]/g, "<img data-title='[握手]' src='" + path + "woshou.gif'/>")
      .replace(/\[胜利\]/g, "<img data-title='[胜利]' src='" + path + "shengli.gif'/>")
      .replace(/\[佩服\]/g, "<img data-title='[佩服]' src='" + path + "peifu.gif'/>")
      .replace(/\[抱拳\]/g, "<img data-title='[抱拳]' src='" + path + "peifu.gif'/>")
      .replace(/\[勾引\]/g, "<img data-title='[勾引]' src='" + path + "gouyin.gif'/>")
      .replace(/\[拳头\]/g, "<img data-title='[拳头]' src='" + path + "quantou.gif'/>")
      .replace(/\[差劲\]/g, "<img data-title='[差劲]' src='" + path + "chajin.gif'/>")
      .replace(/\[干杯\]/g, "<img data-title='[干杯]' src='" + path + "cheer.gif'/>")
      .replace(/\[no\]/g, "<img data-title='[no]' src='" + path + "no.gif'/>")
      .replace(/\[ok\]/g, "<img data-title='[ok]' src='" + path + "ok.gif'/>")
      .replace(/\[NO\]/g, "<img data-title='[NO]' src='" + path + "no.gif'/>")
      .replace(/\[OK\]/g, "<img data-title='[OK]' src='" + path + "ok.gif'/>")
      .replace(/\[给力\]/g, "<img data-title='[给力]' src='" + path + "geili.gif'/>")
      .replace(/\[飞吻\]/g, "<img data-title='[飞吻]' src='" + path + "feiwen.gif'/>")
      .replace(/\[跳跳\]/g, "<img data-title='[跳跳]' src='" + path + "tiao.gif'/>")
      .replace(/\[跳\]/g, "<img data-title='[跳]' src='" + path + "tiao.gif'/>")
      .replace(/\[发抖\]/g, "<img data-title='[发抖]' src='" + path + "fadou.gif'/>")
      .replace(/\[怄火\]/g, "<img data-title='[怄火]' src='" + path + "dajiao.gif'/>")
      .replace(/\[大叫\]/g, "<img data-title='[大叫]' src='" + path + "dajiao.gif'/>")
      .replace(/\[转圈\]/g, "<img data-title='[转圈]' src='" + path + "zhuanquan.gif'/>")
      .replace(/\[磕头\]/g, "<img data-title='[磕头]' src='" + path + "ketou.gif'/>")
      .replace(/\[回头\]/g, "<img data-title='[回头]' src='" + path + "huitou.gif'/>")
      .replace(/\[跳绳\]/g, "<img data-title='[跳绳]' src='" + path + "tiaosheng.gif'/>")
      .replace(/\[挥手\]/g, "<img data-title='[挥手]' src='" + path + "huishou.gif'/>")
      .replace(/\[激动\]/g, "<img data-title='[激动]' src='" + path + "jidong.gif'/>")
      .replace(/\[街舞\]/g, "<img data-title='[街舞]' src='" + path + "tiaowu.gif'/>")
      .replace(/\[献吻\]/g, "<img data-title='[献吻]' src='" + path + "xianwen.gif'/>")
      .replace(/\[左太极\]/g, "<img data-title='[左太极]' src='" + path + "zuotaiji.gif'/>")
      .replace(/\[右太极\]/g, "<img data-title='[右太极]' src='" + path + "youtaiji.gif'/>")
    return content
  },
  getStyle(obj, attr) {
    return window.getComputedStyle(obj)[attr]
  },
  pullUpComFn(that, paramData, getList, fn) { // 上拉-加载-公共方法
    paramData = paramData || { isLoad: true }
    let total = 0
    if (that.paginationData.total !== 'init' && that.scrollList.length > 0) {
      if (that.scrollList.length >= that.paginationData.total) { // 不能继续加载
        if (fn) {
          fn({ isLoadOver: true })
        }
        return
      }
      that.paginationData.number++
    }
    total = that.paginationData.number * that.paginationData.size
    total = Math.min(total, that.paginationData.total)
    if (that.paginationData.total === 'init' || total <= that.paginationData.total) { // 可继续加载
      paramData.isLoad = true
      getList(paramData, res => {
        if (fn) {
          fn({ isLoadOver: false })
        }
      })
    } else { // 不能继续加载
      that.paginationData.number--
      if (fn) {
        fn({ isLoadOver: true })
      }
    }
  },
  createQrCode(QRCode, paramsData, fn) {
    const text = paramsData.text || '请重试！'
    QRCode.toCanvas(paramsData.canvas, text, function(res) {
      // console.log(res)
      if (fn) {
        fn(res)
      }
    })
  }
}
